from dao.questions_bank_dao import QuestionsBankDAO
from utils import log_info, log_error, log_exception

class QuestionsBankService:
    def __init__(self):
        self.dao = QuestionsBankDAO()

    def get_page_data(self, page_num, page_size, search_query=None, filter_la=False, filter_lb=False, filter_lc=False):
        """获取指定页的数据，并进行必要的格式转换"""
        try:
            data = self.dao.get_page_data(page_num, page_size, search_query, filter_la, filter_lb, filter_lc)
            # 进行数据格式转换
            for item in data:
                # 转换题型为文字描述
                item['type_text'] = '单选' if item['type'] == 1 else '多选' if item['type'] == 2 else '未知'
                # 处理图片显示
                item['has_image'] = '有' if (item['F'] and isinstance(item['F'], str) and (item['F'].startswith('data:image/') or item['F'].startswith('img/'))) else '无'
            return data
        except Exception as e:
            log_exception(f"获取分页数据失败: {e}")
            return []

    def update_question(self, question_id, updated_data):
        """更新题目数据"""
        try:
            # 数据验证
            if not question_id:
                log_error("更新题目失败", "题目ID不能为空")
                return False

            if not updated_data:
                log_error("更新题目失败", "更新数据不能为空")
                return False

            # 调用DAO层更新数据
            return self.dao.update_question(question_id, updated_data)
        except Exception as e:
            log_exception(f"更新题目失败: {e}")
            return False

    def get_question_by_id(self, question_id):
        """根据ID获取题目"""
        try:
            question = self.dao.get_question_by_id(question_id)
            if question:
                # 转换题型为文字描述
                question['type_text'] = '单选' if question['type'] == 1 else '多选' if question['type'] == 2 else '未知'
            return question
        except Exception as e:
            log_exception(f"根据ID获取题目失败: {e}")
            return None

    def get_filtered_records_count(self, search_query=None, filter_la=False, filter_lb=False, filter_lc=False):
        """获取筛选后的记录总数"""
        try:
            return self.dao.get_total_records(search_query, filter_la, filter_lb, filter_lc)
        except Exception as e:
            log_exception(f"获取筛选记录数失败: {e}")
            return 0